import { APPOINTMENT_NOTICE_ID, RESPONSE_CODE } from "@/common/config"
import { handleOrderAccept, handleOrderComplete, handleOrderList, handleOrderReject } from "@/common/service"
import { handleLoginCallback, showToast, subscribeMessage } from "@/common/util"
import { IOrderAcceptResponse, IOrderCompleteResponse, IOrderDetailData, IOrderListResponse, IOrderRejectResponse, IResponseSuccess } from "@/typing"
import Taro from "@tarojs/taro"
import { useEffect, useState } from "react"

interface IOrderDetailDataPromise {
    list: Array<IOrderDetailData>,
    code: number
}
const useBlogAction = () => {
    const handleOrderListAjax = async (orderStatus, page): Promise<IOrderDetailDataPromise> => {
        return new Promise(async (resolve, reject) => {
            const orderRes = await handleOrderList(orderStatus, page) as IResponseSuccess<IOrderListResponse>
            if (orderRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
                const { code, msg, data } = orderRes.data;
                if (code === RESPONSE_CODE.SUCCESS) {
                    const list = data.data;
                    if (list.length === 0) {

                        resolve({
                            list: [],
                            code,
                        })
                    } else {
                        resolve({
                            list,
                            code
                        })
                    }

                } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
                    resolve({
                        list: [],
                        code,
                    })
                } else if (code === RESPONSE_CODE.ERROR) {
                    // throw new Error("请求异常");
                    resolve({
                        list: [],
                        code,
                    })

                }
                else {
                    showToast(msg)
                }
            }
        })




    }
    const [callMobile, setCallMobile] = useState('')
    const [mobile, setMobile] = useState('')
    const [wechat, setWechat] = useState('')
    const [chatDialogShow, setChatDialogShow] = useState(false)
    const [tabIndex, setTabIndex] = useState('0')

    const [orderDetail, setOrderDetail] = useState<IOrderDetailData>()
    const [detailShow, setDetailShow] = useState(false)
    const [acceptPage, setAcceptPage] = useState(1)
    const [waitPage, setWaitPage] = useState(1)
    const [finishedPage, setFinishedPage] = useState(1)
    const [cancelPage, setCancelPage] = useState(1)


    const [acceptOrderList, setAcceptOrderList] = useState<Array<IOrderDetailData>>([])
    const [waitingOrderList, setWaitingOrderList] = useState<Array<IOrderDetailData>>([])
    const [finishedOrderList, setFinisherOrderList] = useState<Array<IOrderDetailData>>([])
    const [cancleOrderList, setCancelOrderList] = useState<Array<IOrderDetailData>>([])
    const [noFinishedData, setNoFinishedData] = useState(false)
    const [nocancelData, setNoCancelData] = useState(false)
    const [noWaitingData, setNoWaitingData] = useState(false)
    const [noAcceptData, setNoAcceptData] = useState(false)


    let orderTimeOut;

    const handleAcceptOrderList = (isReset?: boolean) => {
        handleOrderListAjax(0, isReset ? 1 : acceptPage).then(orderData => {
            if (orderData.code === RESPONSE_CODE.SUCCESS) {
                if (orderData.list.length === 0) {
                    setNoAcceptData(true)
                    return
                }
                // console.log(orderData.list)

                setAcceptOrderList(prev => isReset ? orderData.list : [...prev, ...orderData.list]);

            }

        })

    }
    const handleWaitingOrderList = (isReset?: boolean) => {
        handleOrderListAjax(1, isReset ? 1 : waitPage).then(orderData => {
            if (orderData.code === RESPONSE_CODE.SUCCESS) {
                if (orderData.list.length === 0) {
                    setNoWaitingData(true)
                    return
                }

                setWaitingOrderList(prev => isReset ? orderData.list : [...prev, ...orderData.list]);

            }



        })

    }
    const handleFinishedOrderList = (isReset?: boolean) => {
        handleOrderListAjax(2, isReset ? 1 : finishedPage).then(orderData => {
            if (orderData.code === RESPONSE_CODE.SUCCESS) {
                if (orderData.list.length === 0) {
                    setNoFinishedData(true)
                    return
                }

                setFinisherOrderList(prev => isReset ? orderData.list : [...prev, ...orderData.list]);

            }



        })

    }
    const handleCancelOrderList = (isReset?: boolean) => {

        handleOrderListAjax(-1, isReset ? 1 : cancelPage).then(orderData => {
            if (orderData.code === RESPONSE_CODE.SUCCESS) {

                if (orderData.list.length === 0) {
                    setNoCancelData(true)
                    return
                }
                setCancelOrderList(prev => isReset ? orderData.list : [...prev, ...orderData.list]);


            }

        })

    }
    const handleInitAllTabList = (isReset?: boolean) => {
        handleOrderListAjax(1, waitPage).then(orderData => {
            if (orderData.code === RESPONSE_CODE.SUCCESS) {
                setWaitingOrderList(prev => isReset ? orderData.list : [...prev, ...orderData.list]);


                handleFinishedOrderList(isReset);

                // handleWaitingOrderList();
            } else if (orderData.code === RESPONSE_CODE.LOGIN_EXPIRE || orderData.code === RESPONSE_CODE.LOGIN_NEED) {
                handleLoginCallback(() => handleInitAllTabList());
            }

        })
    }
    const handleCancelOrderActionT = async (orderId, orderIndex) => {
        Taro.showLoading({
            title: '',
            mask: true
        })
        const cancelRes = await handleOrderReject(orderId) as IResponseSuccess<IOrderRejectResponse>

        Taro.hideLoading({

        })
        if (cancelRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
            const { code, msg } = cancelRes.data;
            if (code === RESPONSE_CODE.SUCCESS) {
                showToast(msg)
                acceptOrderList.splice(orderIndex, 1)
                setAcceptOrderList([...acceptOrderList])
                orderTimeOut = setTimeout(() => {
                    setCancelOrderList([])
                    setCancelPage(1)
                    handleCancelOrderList()

                }, 500);
                // handleInitOrder(orderInfo?.id)

            } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
                handleLoginCallback(() => handleCancelOrderActionT(orderId, orderIndex));
            } else if (code === RESPONSE_CODE.ERROR) {
                throw new Error("请求异常");

            } else {
                showToast(msg)
            }
        } else {

            showToast('服务器错误')
        }
    }
    const handleCancelOrderAction = (orderId, orderIndex) => {

        Taro.showModal({
            title: '提示',
            content: '确定拒绝该订单吗？',
            success: async function (res) {
                if (res.confirm) {
                    handleCancelOrderActionT(orderId, orderIndex)


                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }
    const handleShowOrderAction = (orderInfo) => {
        setDetailShow(true)
        setOrderDetail(orderInfo)
    }
    const handleAcceptOrderAction = async ({ orderId, orderIndex, orderPhone, wechat }) => {

        let acceptData = {
            id: orderId,

        }


        setMobile(orderPhone)
        setWechat(wechat)

        Taro.showLoading({
            title: '',
            mask: true
        })

        const acceptRes = await handleOrderAccept(acceptData) as IResponseSuccess<IOrderAcceptResponse>


        if (acceptRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
            Taro.hideLoading({

            })
            const { code, msg } = acceptRes.data;
            if (code === RESPONSE_CODE.SUCCESS) {
                showToast(msg)


                acceptOrderList.splice(orderIndex, 1)
                setAcceptOrderList([...acceptOrderList])
                setTabIndex('1')
                orderTimeOut = setTimeout(() => {
                    Taro.hideLoading({

                    })
                    setWaitingOrderList([])
                    setWaitPage(1)
                    handleWaitingOrderList()

                    
              
                }, 500);
                subscribeMessage([APPOINTMENT_NOTICE_ID]).then(()=>{
                   
                    setChatDialogShow(true)
                })
           

            } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
                handleLoginCallback(() => handleAcceptOrderAction(orderId));
            } else if (code === RESPONSE_CODE.ERROR) {
                throw new Error("请求异常");

            } else {
                showToast(msg)
            }
        }

    }

    const handleCompleteOrderActionT = async (orderId, orderIndex) => {
        Taro.showLoading({
            title: '',
            mask: true
        })
        const cancelRes = await handleOrderComplete(orderId) as IResponseSuccess<IOrderCompleteResponse>

        Taro.hideLoading({

        })
        if (cancelRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
            const { code, msg } = cancelRes.data;
            if (code === RESPONSE_CODE.SUCCESS) {
                showToast(msg)
                waitingOrderList.splice(orderIndex, 1)
                setWaitingOrderList([...waitingOrderList])
                orderTimeOut = setTimeout(() => {
                    setFinisherOrderList([])
                    setFinishedPage(1)
                    handleFinishedOrderList()

                }, 500);
                // handleInitOrder(orderInfo?.id)

            } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
                handleLoginCallback(() => handleCompleteOrderActionT(orderId, orderIndex));
            } else if (code === RESPONSE_CODE.ERROR) {
                throw new Error("请求异常");

            } else {
                showToast(msg)
            }
        } else {

            showToast('服务器错误')
        }
    }
    const handleCompleteOrderAction = (orderId, orderIndex) => {
        Taro.showModal({
            title: '提示',
            content: '确定完成该订单吗？',
            success: async function (res) {
                if (res.confirm) {
                    handleCompleteOrderActionT(orderId, orderIndex)


                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }
    const handleResetData = () => {

        setAcceptPage(1)
        setWaitPage(1)
        setFinishedPage(1)
        setCancelPage(1)
    }
    const handleShowCallAction = (mobile, wechat) => {
        setMobile(mobile);
        setWechat(wechat);
        setChatDialogShow(true)
    }
    useEffect(() => {
        if (acceptPage > 1 && !noAcceptData) {
            handleAcceptOrderList()
        }

    }, [acceptPage])
    useEffect(() => {
        if (waitPage > 1 && !noWaitingData) {
            handleWaitingOrderList()
        }

    }, [waitPage])
    useEffect(() => {
        if (finishedPage > 1 && !noFinishedData) {
            handleFinishedOrderList()
        }

    }, [finishedPage])
    useEffect(() => {
        if (cancelPage > 1 && !nocancelData) {
            handleCancelOrderList()
        }


    }, [cancelPage])
    useEffect(() => {

        return () => {
            clearTimeout(orderTimeOut)
        };
    }, []);
    return {
        acceptPage,
        waitPage,
        finishedPage,
        cancelPage,
        acceptOrderList,
        waitingOrderList,
        finishedOrderList,
        cancleOrderList,
        detailShow,
        orderDetail,
        chatDialogShow,
        wechat,
        mobile,
        callMobile,
        tabIndex,
        setNoFinishedData,
        setNoAcceptData,
        setNoWaitingData,
        setNoCancelData,
        setChatDialogShow,
        setTabIndex,
        setCallMobile,
        setCancelOrderList,
        setAcceptOrderList,
        setDetailShow,
        setAcceptPage,
        setWaitPage,
        setFinishedPage,
        setCancelPage,
        handleResetData,
        handleWaitingOrderList,
        handleFinishedOrderList,
        handleCancelOrderList,
        handleAcceptOrderList,
        handleInitAllTabList,
        handleCancelOrderAction,
        handleShowOrderAction,
        handleAcceptOrderAction,
        handleShowCallAction,
        handleCompleteOrderAction
    }
}
export default useBlogAction